package com.ruoyi.ring.service.impl;

import cn.hutool.core.convert.Convert;
import com.ruoyi.common.enums.MemberTypeEnums;
import com.ruoyi.common.enums.YesOrNoEnums;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.ring.domain.RingInteractiveSharing;
import com.ruoyi.ring.domain.dto.GroupQueryDTO;
import com.ruoyi.ring.domain.dto.QueryShareDTO;
import com.ruoyi.ring.domain.dto.ShareSignAddDTO;
import com.ruoyi.ring.domain.vo.GroupResultVO;
import com.ruoyi.ring.domain.vo.RingGroupResultVO;
import com.ruoyi.ring.domain.vo.ShareListVO;
import com.ruoyi.ring.mapper.RingGroupMapper;
import com.ruoyi.ring.mapper.RingInteractiveSharingMapper;
import com.ruoyi.ring.service.IAppGroupService;
import com.ruoyi.ring.service.IRingInteractiveSharingService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 互动分享Service业务层处理
 * 
 * @author liuwp
 * @date 2025-11-21
 */
@Service
public class RingInteractiveSharingServiceImpl implements IRingInteractiveSharingService 
{

    @Resource
    private IAppGroupService appGroupService;
    @Resource
    private RingInteractiveSharingMapper ringInteractiveSharingMapper;
    @Resource
    private RingGroupMapper ringGroupMapper;

    /**
     * 查询互动分享
     * 
     * @param id 互动分享主键
     * @return 互动分享
     */
    @Override
    public RingInteractiveSharing selectRingInteractiveSharingById(Long id)
    {
        return ringInteractiveSharingMapper.selectRingInteractiveSharingById(id);
    }

    /**
     * 查询互动分享列表
     * 
     * @param ringInteractiveSharing 互动分享
     * @return 互动分享
     */
    @Override
    public List<RingInteractiveSharing> selectRingInteractiveSharingList(RingInteractiveSharing ringInteractiveSharing)
    {
        return ringInteractiveSharingMapper.selectRingInteractiveSharingList(ringInteractiveSharing);
    }

    /**
     * 根据业务主键查询一条记录：互动分享
     *
     * @param ringInteractiveSharing 互动分享
     * @return 互动分享
     */
    @Override
    public RingInteractiveSharing selectOneRingInteractiveSharing(RingInteractiveSharing ringInteractiveSharing)
    {
        return ringInteractiveSharingMapper.selectOneRingInteractiveSharing(ringInteractiveSharing);
    }

    /**
     * 新增互动分享
     * 
     * @param ringInteractiveSharing 互动分享
     * @return 结果
     */
    @Override
    public int insertRingInteractiveSharing(RingInteractiveSharing ringInteractiveSharing)
    {
        ringInteractiveSharing.setCreateTime(DateUtils.getNowDate());
        return ringInteractiveSharingMapper.insertRingInteractiveSharing(ringInteractiveSharing);
    }

    /**
     * 修改互动分享
     * 
     * @param ringInteractiveSharing 互动分享
     * @return 结果
     */
    @Override
    public int updateRingInteractiveSharing(RingInteractiveSharing ringInteractiveSharing)
    {
        ringInteractiveSharing.setUpdateTime(DateUtils.getNowDate());
        return ringInteractiveSharingMapper.updateRingInteractiveSharing(ringInteractiveSharing);
    }

    @Override
    public int updateRingInteractiveSharingCondition(RingInteractiveSharing ringInteractiveSharing, RingInteractiveSharing ringInteractiveSharingCondition)
    {
                ringInteractiveSharing.setUpdateTime(DateUtils.getNowDate());
        return ringInteractiveSharingMapper.updateRingInteractiveSharingCondition(ringInteractiveSharing, ringInteractiveSharingCondition);
    }

    /**
     * 批量删除互动分享
     * 
     * @param ids 需要删除的互动分享主键
     * @return 结果
     */
    @Override
    public int deleteRingInteractiveSharingByIds(Long[] ids)
    {
        return ringInteractiveSharingMapper.deleteRingInteractiveSharingByIds(ids);
    }

    /**
     * 删除互动分享信息
     * 
     * @param id 互动分享主键
     * @return 结果
     */
    @Override
    public int deleteRingInteractiveSharingById(Long id)
    {
        return ringInteractiveSharingMapper.deleteRingInteractiveSharingById(id);
    }

    /**
     * 条件删除互动分享
     *
     * @param ringInteractiveSharing 互动分享
     * @return 结果
     */
    @Override
    public int deleteRingInteractiveSharingByCondition(RingInteractiveSharing ringInteractiveSharing)
    {
        return ringInteractiveSharingMapper.deleteRingInteractiveSharingByCondition(ringInteractiveSharing);
    }

    /**
     * 今日签分享 app
     */
    @Override
    public int addManualShareSign(ShareSignAddDTO dto){
        long userId = SecurityUtils.getUserId();
        Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD,DateUtils.getDate());
        RingInteractiveSharing interactiveSharing = ringInteractiveSharingMapper.selectOneRingInteractiveSharing(Builder.of(RingInteractiveSharing::new).
                with(RingInteractiveSharing::setGroupId,dto.getGroupId()).
                with(RingInteractiveSharing::setUserId,userId).
                with(RingInteractiveSharing::setDailyValue,date).
                with(RingInteractiveSharing::setIsAutomatic,YesOrNoEnums.NO.getCode()).build());
        if(interactiveSharing != null){
            RingInteractiveSharing ringInteractiveSharing = Convert.convert(RingInteractiveSharing.class,dto);
            ringInteractiveSharing.setId(interactiveSharing.getId());
            ringInteractiveSharing.setUserId(userId);
            ringInteractiveSharing.setDailyValue(date);
            return ringInteractiveSharingMapper.updateRingInteractiveSharing(ringInteractiveSharing);
        }else {
            RingInteractiveSharing ringInteractiveSharing = Convert.convert(RingInteractiveSharing.class,dto);
            ringInteractiveSharing.setUserId(userId);
            ringInteractiveSharing.setDailyValue(date);
            return ringInteractiveSharingMapper.insertRingInteractiveSharing(ringInteractiveSharing);
        }
    }
    /**
     * 自动今日签分享 app
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addAutomaticShareSign(String deviceSn){
        long userId = SecurityUtils.getUserId();
        Date date = DateUtils.dateTime(DateUtils.YYYY_MM_DD,DateUtils.getDate());
        GroupQueryDTO queryDTO = new GroupQueryDTO();
        queryDTO.setUserId(userId);
        queryDTO.setMemberType(MemberTypeEnums.GROUP_OWNER.getCode());
        List<RingGroupResultVO> ringGroupResultVOList = ringGroupMapper.queryGroupList(queryDTO);
        try {
            if(ringGroupResultVOList.size() > 0){
                for(RingGroupResultVO ringGroupResultVO : ringGroupResultVOList){
                    long groupId = ringGroupResultVO.getId();
                    List<GroupResultVO> groupResultVOList = appGroupService.querySleep(groupId);
                    int maxScore = groupResultVOList.stream()
                            .mapToInt(GroupResultVO::getValue)
                            .max()
                            .orElse(0); // 若没有成员，默认最大值为0

                    for (GroupResultVO groupResultVO : groupResultVOList){
                        if(maxScore > 0 && groupResultVO.getValue() == maxScore){
                            long memberUserId = groupResultVO.getUserId();
                            RingInteractiveSharing interactiveSharing = ringInteractiveSharingMapper.selectOneRingInteractiveSharing(Builder.of(RingInteractiveSharing::new).
                                    with(RingInteractiveSharing::setGroupId,groupId).
                                    with(RingInteractiveSharing::setUserId,memberUserId).
                                    with(RingInteractiveSharing::setDailyValue,date).
                                    with(RingInteractiveSharing::setIsAutomatic,YesOrNoEnums.YES.getCode()).build());
                            if(interactiveSharing == null){
                                RingInteractiveSharing ringInteractiveSharing = new RingInteractiveSharing();
                                ringInteractiveSharing.setGroupId(groupId);
                                ringInteractiveSharing.setUserId(memberUserId);
                                ringInteractiveSharing.setContent(groupResultVO.getUserName()+"用户今日睡眠最佳");
                                ringInteractiveSharing.setDailyValue(date);
                                ringInteractiveSharing.setIsAutomatic(YesOrNoEnums.YES.getCode());
                                ringInteractiveSharingMapper.insertRingInteractiveSharing(ringInteractiveSharing);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public List<ShareListVO> queryShareList(QueryShareDTO shareDTO) {
        return ringInteractiveSharingMapper.queryShareList(shareDTO);
    }
}
